<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\Plugin\Greeting\Action\Workbench;

use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\Utils\Codec\Json;
use MoChat\App\Common\Middleware\WorkbenchAuthMiddleware;
use MoChat\App\WorkEmployee\Contract\WorkEmployeeContract;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;
use MoChat\Plugin\Greeting\Action\Dashboard\Traits\MediumTrait;
use MoChat\Plugin\Greeting\Contract\GreetingContract;

/**
 * 欢迎语-列表.
 *
 * Class Index.
 * @Controller
 */
class Index extends AbstractAction
{
    use ValidateSceneTrait;
    use MediumTrait;

    /**
     * @Inject
     * @var WorkEmployeeContract
     */
    protected $workEmployeeService;

    /**
     * @Inject
     * @var GreetingContract
     */
    private $greetingService;

    /**
     * @RequestMapping(path="/workbench/greeting/index", methods="get")
     * @Middlewares({
     *     @Middleware(WorkbenchAuthMiddleware::class)
     * })
     * @return array 返回数组
     */
    public function handle(): array
    {
        // 获取当前登录用户
        $user = user();
        // 判断用户绑定企业信息
        if (! isset($user['corpId'])) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '未选择登录企业，不可操作');
        }
        $params['userId'] = (int) $user['logUserId'];
        $params['corpId'] = $user['corpId'];
        $params['employeeId'] = $user['id'];
        $params['name'] = $this->request->input('name', '');
        // 参数验证
        $this->validated($this->request->all());

        $list = $this->greetingService->getGreetingsByCorpIdEmployeeIdWords($params['corpId'], $params['employeeId'], $params['name']);

        foreach ($list as &$item) {
            $employees = $this->workEmployeeService->getWorkEmployeesById(Json::decode($item['employees']), ['id', 'name', 'avatar']);
            foreach ($employees as &$emp) {
                $emp['avatar'] = file_full_url($emp['avatar']);
            }
            unset($emp);
            $item['employees'] = $employees;
            if (! empty($item['mediumId'])) {
                $item['mediumContent'] = $this->handleMedium(Json::decode($item['mediumId']));
            }
            if ($item['spanWelcomeStatus'] === 1) {
                $item['spanWelcome'] = Json::decode($item['spanWelcome']);
                foreach ($item['spanWelcome'] as $k => $v) {
                    $item['spanWelcome'][$k]['mediumContent'] = $this->handleMedium($v['mediumId']);
                }
            }
        }
        unset($item);
        $now = null;
        if (! empty($list)) {
            $now = $list[0];
            unset($list[0]);
        }

        return ['now' => $now, 'history' => array_merge($list)];
    }
}
